package cn.datawin.task.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import com.gargoylesoftware.htmlunit.util.Cookie;

public class WebDriver {

	private static ArrayList<loginDriver> drivers = new ArrayList<loginDriver>();
	static Random random = new Random();

	static {
		drivers.add(new loginDriver(true));
		drivers.add(new loginDriver(true));
		drivers.add(new loginDriver(true));
	}

	public static loginDriver getDriver() {
		return drivers.get(random.nextInt(drivers.size()));
	}

	public static String get(String url, List<org.apache.http.cookie.Cookie> list) {
		loginDriver driver = getDriver();
		driver.serCookie(list);
		synchronized (driver) {
			try {
				driver.get(url);
			} catch (WebDriverException e) {
				System.out.println(e);
			}
			return driver.getPageSource();
		}
	}
	
	static class loginDriver extends HtmlUnitDriver{
		public  void serCookie(List<org.apache.http.cookie.Cookie> list) {
			List<Cookie> cookies = Cookie.fromHttpClient(list);
			for(Cookie cookie :cookies){
				getWebClient().getCookieManager().addCookie(cookie);
			}
		}
		
		public loginDriver() {
			super();
		}
		
		public loginDriver(boolean f) {
			super(f);
		}
		
		
	}

}
